package mobileann.mafamily.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import mobileann.mafamily.act.main.FS;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.tencent.tauth.IRequestListener;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

/**
 * 下载icon图像的工具类
 * <br>loadImage(url) 异步下载图片
 * <br>saveImgToSD(url)将图片存储到本地
 * <br>UserLogoFilesPath() 获取到存取本地图片文件夹的路径
 * @author ADRIAN
 */
public class IconImageUtils {
	private static IconImageUtils iconImageUtils;

	private IconImageUtils() {

	}

	public static IconImageUtils getInstance() {
		if (iconImageUtils == null) {
			iconImageUtils = new IconImageUtils();
		}
		return iconImageUtils;
	}

	/**
	 * DefaultHttpClient下载图像
	 * @param url
	 * @return
	 * @author ADRIAN.2015.7.28.10.52
	 */
	public Bitmap loadImage(String url) {  
		if (url == null) { return null;}
		Bitmap bitmap = null;  
		HttpClient client = new DefaultHttpClient();  
		HttpResponse response = null;  
		InputStream inputStream = null;  
		try {  
			response = client.execute(new HttpGet(url));  
			HttpEntity entity = response.getEntity();  
			inputStream = entity.getContent(); 
			bitmap = BitmapFactory.decodeStream(inputStream);  
		} catch (ClientProtocolException e) {  
			e.printStackTrace();  
		} catch (IOException e) {  
			e.printStackTrace();  
		}  
		return bitmap;  
	}  


	/**
	 * 将图片保存到SD卡
	 * @param iconName
	 * @param bitmap
	 */
	public void saveImgToSD(String uid, String iconName,Bitmap bitmap) {
		if (uid == null) return ;
		if (bitmap == null) return ; 
		if (iconName == null) return ; // 只要有一种情况为空,都返回,避免空指针异常.

		StringBuilder sb = new StringBuilder(128);
		sb.append(UserLogoFilesPath());
		sb.append(File.separator);
		sb.append(iconName);
		File photoFile = new File(sb.toString()); //在指定路径下创建文件
		//File photoFile = new File(UserLogoFilesPath(), iconName); //在指定路径下创建文件
		FileOutputStream fileOutputStream = null;
		try {
			fileOutputStream = new FileOutputStream(photoFile);
			if (bitmap != null) {
				if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream)) {
					fileOutputStream.flush();
					SPUtils.setMD5ImgUrl(uid, iconName);
				}
			}
		} catch (FileNotFoundException e) {
			if (photoFile!=null)
				photoFile.delete();
			e.printStackTrace();
		} catch (IOException e) {
			if (photoFile!=null) 
				photoFile.delete();
			e.printStackTrace();
		} finally {
			try {
				if (fileOutputStream != null) {
					fileOutputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 主要功能：
	 * <br>1.创建图片存储的路径,相当于存储icon图像的根路径
	 * @return
	 * @annotation ADRIAN.2015.7.17.10.42
	 */
	public synchronized String UserLogoFilesPath() {
		String path = FS.getInstance().getFilesDir().getAbsolutePath()
				+ File.separator + "MABaby" + File.separator
				+ "MAFamilyUserLogo";
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			path = (Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator
					+ "MABaby" + "/MAFamilyUserLogo");
		}
		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdir();
		}
		dir = null;
		return path;
	}

	//========================================================
	/**
	 * 异步下载图片，如果图片已经有，就不下载。若无，怎下载。 <br>
	 * 配合IconImgeLoadTask类使用
	 * 
	 * @param imgUrl
	 * @author ADRIAN.2015.7.17.11.50
	 */
	public void downIconImgIfNotExits(String phone, String imgUrl) {
		// 不管头像存在不存在都要更新以下里边的内容，以免出现跟屁虫被清理 #ADRIAN.2015.7.28.13.38
		String iconName = getIconName(imgUrl);
		StringBuffer sbImgPath = new StringBuffer(128);
		sbImgPath.append(UserLogoFilesPath());
		sbImgPath.append(File.separator);
		sbImgPath.append(iconName);
		File img = new File(sbImgPath.toString());
		boolean isExists = img.exists();
		if (!isExists) {
			//----如果没有此文件-----------
			// 先判断是否是本人的UID,然后进行判断是不是有这个图片的(逻辑)
			String localUID = SPUtils.getUID();
			if (localUID.equals(phone)) { // 如果是本人的UID, 则添加判断本地剪裁的图片, 是否下载的图片
				StringBuffer sbLocalIcon = new StringBuffer(64);
				sbLocalIcon.append(IconImageUtils.getInstance().UserLogoFilesPath());
				sbLocalIcon.append(File.separator);
				sbLocalIcon.append(SPUtils.getMD5ImgUrl(phone));
				File localIcon = new File(sbLocalIcon.toString());/*IconImageUtils.getInstance().UserLogoFilesPath() + File.separator +SPUtils.getMD5ImgUrl(phone)*/
				if (localIcon.exists()) { // 如果本地修改的图像存在,将本地图片进行名字修改
					//					StringBuffer sbPhotoFile = new StringBuffer(64);
					//					sbPhotoFile.append(IconImageUtils.getInstance().UserLogoFilesPath());
					//					sbPhotoFile.append(File.separator);
					//					sbPhotoFile.append(IconImageUtils.getInstance().getIconName(imgUrl));
					File photoFile = new File(sbImgPath.toString());/*IconImageUtils.getInstance().UserLogoFilesPath() + File.separator + IconImageUtils.getInstance().getIconName(imgUrl)*/
					localIcon.renameTo(photoFile);
					SPUtils.setMD5ImgUrl(phone, IconImageUtils.getInstance().getIconName(imgUrl));
					if (localIcon.exists()) {
						localIcon.delete();
					}
					localIcon = null;
					photoFile = null;
					return ; // 处理完这个图片加载逻辑,就返回此方法,不在往下执行
				}
			}
			//----------------------------			
		}
		// 如果上面的语句没有执行(未return),则执行下面的语句
		SPUtils.setMD5ImgUrl(phone, iconName);
		if(!isExists){
			new IconImageLoadTask(phone).execute(imgUrl);
		}
	}

	/**
	 * 主要功能:
	 * 如果本人的图片,在本地已经存在.将那个图片改名后,删除
	 * @param phone
	 * @param imgUrl
	 * @return
	 */
	public boolean whetherLocalImgeIn(String phone, String imgUrl) {
		//------------------------
		// 先判断是否是本人的UID,然后进行判断是不是有这个图片的(逻辑)
		String localUID = SPUtils.getUID();
		if (localUID.equals(phone)) { // 如果是本人的UID, 则添加判断本地剪裁的图片, 是否下载的图片
			StringBuffer sbLocalIcon = new StringBuffer(64);
			sbLocalIcon.append(IconImageUtils.getInstance().UserLogoFilesPath());
			sbLocalIcon.append(File.separator);
			sbLocalIcon.append(SPUtils.getMD5ImgUrl(phone));
			File localIcon = new File(sbLocalIcon.toString());/*IconImageUtils.getInstance().UserLogoFilesPath() + File.separator +SPUtils.getMD5ImgUrl(phone)*/
			if (localIcon.exists()) { // 如果本地修改的图像存在,将本地图片进行名字修改
				StringBuffer sbPhotoFile = new StringBuffer(64);
				sbPhotoFile.append(IconImageUtils.getInstance().UserLogoFilesPath());
				sbPhotoFile.append(File.separator);
				sbPhotoFile.append(IconImageUtils.getInstance().getIconName(imgUrl));
				File photoFile = new File(sbPhotoFile.toString());/*IconImageUtils.getInstance().UserLogoFilesPath() + File.separator + IconImageUtils.getInstance().getIconName(imgUrl)*/
				localIcon.renameTo(photoFile);
				SPUtils.setMD5ImgUrl(phone, IconImageUtils.getInstance().getIconName(imgUrl));
				if (localIcon.exists()) {
					localIcon.delete();
				}
				localIcon = null;
				photoFile = null;
				return true; // 处理完这个图片加载逻辑,就返回此方法,不在往下执行
			}
		}
		return false;
	}



	//	public void downIconImgIfNotExits(String phone, String imgUrl) {
	//		String imgPath = UserLogoFilesPath() + SPUtils.getMD5ImgUrl(phone);
	//		File img = new File(imgPath);
	//		if(!img.exists()){
	////		String md5ImgUrl = SPUtils.getMD5ImgUrl(phone);
	////		if (!MD5.getMD5FromUrl(imgUrl).equals(md5ImgUrl)) {
	//			new IconImageLoadTask().execute(imgUrl);
	//			// 先将icon的网址存入本地文件 #ADRIAN.2015.7.16.17.03
	//			SPUtils.setMD5ImgUrl(phone, MD5.getMD5FromUrl(imgUrl));
	//		}
	//	}

	/**
	 * @deprecated
	 * @param imgUrl
	 * @param 这是多余
	 * @return
	 */
	public String getIconName(String imgUrl, String 这是多余){
		return imgUrl.substring(imgUrl.lastIndexOf("/") + 1);
	}

	/**
	 * 
	 * @param imgUrl
	 * @return  返回MD5加密后的文件，用作文件名称
	 */
	public String getIconName(String imgUrl) {
		return MD5.getMD5FromUrl(imgUrl);
	}

	/**
	 * http://avatar.mobileann.com/1438861920_20359061
	 * with "/" split  and "_" split
	 * @deprecated 未用到
	 * @return
	 */
	public String getNetworkIconSplitName(String imgUrl){
		String substring = imgUrl.substring(imgUrl.lastIndexOf("/")+1);
		String[] split = substring.split("_");
		if (split.length == 2) {
			return split[0];
		}
		return null;
	}

	/**
	 * 解析本地图片后缀名"#"
	 * @deprecated 未用到
	 * @param iconName
	 * @return
	 */
	public String getLocalIconSplitName(String iconName){
		String[] split = iconName.split("#");
		if (2 == split.length) {
			return split[1];
		}
		return null;
	}

}
